'use strict';

app.controller('managementCtrl', ['$scope', '$http', '$stateParams', '$rootScope', '$filter', '$location', '$timeout', 'lodash', function ($scope, $http, $stateParams, $rootScope, $filter, $location, $timeout, lodash) {
    $scope.urlProposer = "";   // 提出人
    $scope.urlSource = "";   // 需求来源
    $scope.urlPdmAcount = "";   // pdm负责人
    $scope.urlPdmGroup = "";   // pdm分组
    $scope.urlAcceptAccount = "";   // 受理人
    $scope.urlAppointAcceptAccount = "";  //指定受理人
    $scope.urlMyAccount=$stateParams.accept;
    $rootScope.initBreadcrumb($scope.breadcrumb);
    $scope.breadcrumb.push('需求管理');
    //页面加载时，给headerElement设置元素
    $rootScope.initHeaderElements($scope.settings);

    $scope.setTableHeight = function () {
        $timeout(function () {
            var h = document.documentElement.clientHeight || document.body.clientHeight;
            //框架头部、headerHeight、footerHeight
            h = h - 60 - 40 - 50 - 300;
            $("#dtable").css("height", h + "px");
        })
    }
    $scope.setTableHeight();
    window.onresize = $scope.setTableHeight;
    $scope.$on("$destroy", function () {
        window.onresize = "";
    });

    $scope.settings.searchEle = {
        show: true, //显示查询框
        func: function (keyword) { //点击查询框调用的方法
            $scope.info.searchC.keyword = keyword ? keyword : "";
            searchByKeyword();
        },
        blurFunc: function (keyword) {
            $scope.info.searchC.keyword = keyword ? keyword : "";
        }
    };
    //查询月份按钮
    $scope.settings.dateRadios = {
        show: true,
        radios: config_date_radios,
        init: 1,
        func: function (startDate) {
            $scope.info.searchC.startDate = startDate;
            searchByKeyword()
        }
    }
    var addIssueBtn = {
        show: $rootScope.isMatrixRole(),
        label: "新建需求",
        func: function () {
            createNewDemand();
        }
    };
    var acceptDemand = {
        //show: $rootScope.isMatrixCusRole('pdm'),
        show: $rootScope.isMatrixRole(),
        label: "受理需求（" + $scope.acceptSum + "）",
        btnId: "acceptNum",
        func: function () {
            editAcceptDemand();
        }
    };
    var toCount = {
        show: true,
        label: "查看统计",
        func: function () {
            $scope.toCount();
        }
    };
    $scope.settings.btnEle.push(addIssueBtn);

    if ($rootScope.isMatrixCusRole('pdm')) {
        $scope.settings.btnEle.push(acceptDemand);
    }
    // $scope.settings.btnEle.push(toCount);

    $scope.info = {
        pieData: [], // pie数据
        splineData: [], // spline数据
        viewDay: [], // spline中的横线数据
        isShowPie: true,
        isShowView: true,
        radioModel: 'ACCEPT', // 及时处理
        isPdm: $rootScope.isMatrixCusRole('pdm'),
        isMaster: $rootScope.isMatrixCusRole('dept_charger'),
        isAdmin: $rootScope.isUserCanOperateByRole(),
        iscrtAccount: getUserAccount(),
        sourceList: $rootScope.getSysConfigList('NEED_SOURCE'),//需求来源列表
        searchC: {
            needMasterAccount: "",
            appointAcceptAccount: ""
        }, //查询条件
        acceptCount: 0, //受理需求数
    };
    $scope.info.stepsArray = []; // 进度条设置

    getAllUser();
    getAllUser("pdm");
    setPie();
    setSpline('ACCEPT');
    getUserAcceptCount();
    // $scope.settings.switchs.push({
    //     label: "显示已结束需求",
    //     check: false,
    //     checkFun: function (check) {
    //         $scope.info.searchC.showOnline = check;
    //         searchByKeyword();
    //     }
    // });

    //设置data-table
    $scope.options = {
        rowHeight: 40,
        headerHeight: 40,
        footerHeight: 50,
        columnMode: 'force',
        forceFillColumns: true,
        emptyMessage: '暂无数据！',
        columns: [{
            name: "进度",
            prop: 'status',
            width: 100,
            cellRenderer: function () {
                // return '<rzslider popover="{{getLineStatus($row.status)}}" popover-trigger="mouseenter" popover-placement="bottom" class="matrix-slider" rz-slider-model="$row.status" rz-slider-options="matrix_slider_bar.options"></rzslider>';
                return '<span style="color: red;" ng-if="$row.status==\'FALLBACK\'" title="{{$row.fallbackReason}}">{{$row.fallbackReason}}</span> <rzslider ng-if="$row.status!=\'FALLBACK\'" title="{{getLineStatus($row.status)}}" popover-trigger="mouseenter" popover-placement="bottom" class="matrix-slider" rz-slider-model="$row.status" rz-slider-options="matrix_slider_bar.options"></rzslider>';
            }
        },

            {
                name: "需求标题",
                prop: 'title',
                width: 250,
                cellRenderer: function () {
                    return '<a href="javascript:void(0);"><span ng-click="editDemand($row)">{{$cell}}</span>';
                    // <span style="margin-left: 5px; color: red;" ng-click="clickFALLBACK($row)" ng-if="$row.status == \'ACCEPT\'">回退</span></a>
                    // return '<div ng-dropover ng-dropover-options="{\'triggerEvent\': \'click\', \'verticalOffset\': 10}">' +
                    //        '    <a href="javascript:void(0);"><span ng-click="clickTitle($row)">{{$cell}}</span><span style="margin-left: 5px; color: red;" ng-click="clickFALLBACK($row)" ng-if="$row.status == \'ACCEPT\'">回退</span></a>' +
                    //        '    <div ng-dropover-contents class="arrowed">' +
                    //        '        <div>' +
                    //        '            <p>受理情况：{{$cell}}</p>' +
                    //        '            <p>回退原因： 不予处理</p>' +
                    //        '            <p>追加说明：XXXX <i class="fa fa-plus"> 追加</i></p>' +
                    //        '        </div>' +
                    //        '    </div>' +
                    //        '</div>';
                }
            },
            {name: "状态", width: 100, prop: 'statusName'},
            {name: "来源", width: 100, prop: 'sourceName'},
            {name: "提出人", width: 80, prop: 'proposerName'},
            {name: "创建时间", width: 100, prop: 'createTime'},
            {name: "受理人", width: 100, prop: 'acceptName'},
            {name: "指定受理人", width: 80, prop: 'appointAcceptName'},
            {name: "优先级", width: 100, prop: 'levelName'},
            {
                name: "操作",
                width: 100,
                cellRenderer: function () {
                    return '<a href="javascript:void(0);" ng-click="deleteRow($row)" ng-if="$row.proposerAccount == info.iscrtAccount || info.isAdmin" style="margin-right: 10px;">删除</a>' +
                        '<a href="javascript:void(0);" ng-click="acceptDemand($row)" ng-if="($row.status ==\'DEPARTMENT_REVIEW\') && info.isPdm" style="margin-right: 10px;">受理</a>' +
                        '<a href="javascript:void(0);" ng-click="reviewNeed($row)" ng-if="($row.status ==\'NO_ACCEPT\') && info.isMaster" style="margin-right: 10px;">评审</a>' +
                        '<a href="javascript:void(0);" ng-click="cancelDemand($row)" ng-if="$row.acceptAccount == info.iscrtAccount && $row.status == \'ACCEPT\'" title="取消受理">取消</a>';
                }
            },
            {
                name: "评价",
                width: 100,
                cellRenderer: function () {
                    return '<i class="fa fa-spinner fa-spin fa-2x fa-fw" data-id="{{$row.id}}" style="display: none;" ' +
                        'ng-if="$row.status == \'ONLINE\' || $row.status == \'CLOSED\'">' +
                        '</i><rating class="rating" data-id="{{$row.id}}" ng-model="$row.star" max="5" ' +
                        'ng-if="$row.status == \'ONLINE\' || $row.status == \'CLOSED\'" ' +
                        'readonly="$row.status == \'CLOSED\' && $row.starType==\'USER\'" ' +
                        'ng-change="clickStar($row)"></rating>';
                }
            }
        ],
    };

    // 获取当前用户的受理数量
    function getUserAcceptCount() {
        var url = matrix_product_url +"/need/getAcceptAccountAndStatus?acceptAccount="+ getUserAccount() +"&status=ACCEPT";
        $http.get(url).success(function(result) {
            if(result.code == "0") {
                $scope.info.acceptCount = result.data.length || 0;
                $("#acceptNum").html("受理需求（" + (result.data.length || 0) + "）");
            } else {
                $rootScope.toasterErrorInfo("获取当前用户的受理数量错误！");
            }
        });
    }

    //获取偏好设置
    function setFondness() {
        var fondness = getFondness("/api/v1/need/getNeeds");
        if (fondness) {
            $scope.urlProposer = fondness.proposerAccount || "";
            $scope.urlSource = fondness.source || "";
            $scope.urlPdmAcount = fondness.pdmAcount || "";
            $scope.urlPdmGroup = fondness.pdmGroup || "";
            $scope.urlAcceptAccount = fondness.urlAcceptAccount || "";
            $scope.urlAppointAcceptAccount = fondness.urlAppointAcceptAccount || "";
        }
    }

    // 根据key给进度设置step
    angular.forEach(config_need_status, function (status) {
        $scope.info.stepsArray.push(status.key);
    })

    // 设置进度options
    $scope.matrix_slider_bar = {
        options: {
            // ceil:5,
            showSelectionBar: true,
            // showTicksValues:true,
            readOnly: true,
            stepsArray: $scope.info.stepsArray,
            getSelectionBarColor: function (value) {
                var rtn = value;
                angular.forEach(config_need_status, function (s) {
                    if (value == s.key) {
                        rtn = s.color;
                    }
                })
                return rtn;
            },
            getPointerColor: function (value) {
                var rtn = value;
                angular.forEach(config_need_status, function (s) {
                    if (value == s.key) {
                        rtn = s.color;
                    }
                })
                return rtn;
            },
            translate: function (value, id, which) {
                return ''
            },
        },
    }

    // 获取进度的状态
    $scope.getLineStatus = function (status) {
        var rtn = status;
        angular.forEach(config_need_status, function (s) {
            if (status == s.key) {
                rtn = s.value;
            }
        })
        return rtn;
    }
    //点击显示不同状态的数据
    $scope.clickTab = function (tab) {
        $scope.info.selectTab = tab;
        if (tab != "ALL") {
            $scope.tableData = angular.copy($scope.info.allData);
            if ($scope.tableData) {
                $scope.tableData.splice(0, $scope.tableData.length);
            }
            angular.forEach($scope.info.allData, function (data, index) {
                data.num = index;
                if (data.status == tab) {
                    $scope.tableData.push(data);
                }
            });
        } else {
            $timeout(function () {
                $scope.tableData = angular.copy($scope.info.allData);
            }, 500)
        }
    };

    // 编辑需求
    $scope.editDemand = function (row) {
        window.location.href = "#/app/need/addNeed/edit/"+ row.id +"/"+ ($stateParams.accept || "") +"/"+ ($stateParams.appointAccept || "");
    };

    // 设置pie图
    function setPie() {
        $scope.info.isShowPie = false;
        var url = matrix_product_url + "/need/getStatusCount?statusList=" + JSON.stringify(["NO_ACCEPT", "ACCEPT", "CONFIRM", "DEVING", "ONLINE", "LATED"]);
        $http.get(url).success(function (result) {
            if (result.code == "0") {
                $scope.info.isShowPie = true;
                $scope.info.pieData = [
                    {"label": "新建/未受理（" + result.data.NO_ACCEPT + "个）", "data": result.data.NO_ACCEPT},
                    {"label": "需求受理（" + result.data.ACCEPT + "个）", "data": result.data.ACCEPT},
                    {"label": "需求确认（" + result.data.CONFIRM + "个）", "data": result.data.CONFIRM},
                    {"label": "立项研发（" + result.data.DEVING + "个）", "data": result.data.DEVING},
                    {"label": "完成上线（" + result.data.ONLINE + "个）", "data": result.data.ONLINE},
                    {"label": "延期中（" + result.data.LATED + "个）", "data": result.data.LATED},
                ];
            } else {
                $rootScope.toasterErrorInfo("获取需求状态数据错误！");
            }
        });
    }

    // 切换需求处理
    $scope.switchView = function (status) {
        setSpline(status);
    };

    // 设置spline图
    function setSpline(status) {
        $scope.info.isShowView = false;
        var url = matrix_product_url + "/need/getAcceptanceProbability?type=" + status;
        $http.get(url).success(function (result) {
            if (result.code == "0") {
                var num = 0;
                $scope.info.isShowView = true;
                $scope.info.viewDay = [];
                $scope.info.splineData = [];
                var viewDay = [];
                var splineData = [];
                angular.forEach(result.data, function (data, value) {
                    viewDay.push([num++, value]);
                    splineData.push([num++, data]);
                });
                for (var i = 1; i <= viewDay.length; i++) {
                    $scope.info.viewDay.push([i, viewDay[i - 1][1]]);
                }
                for (var i = 1; i <= splineData.length; i++) {
                    $scope.info.splineData.push([i, splineData[i - 1][1]]);
                }
            } else {
                $rootScope.toasterErrorInfo("获取需求处理数据错误！");
            }
        });
    }

    //跳转SLA统计页面
    $scope.toCount = function () {
        window.location.href = "#/app/need/count";
    };

    // 删除
    $scope.deleteRow = function (row) {
        var confirmParams = {
            "titleData": "提示",
            "bodyData": "确定删除需求【" + row.title + "】吗？"
        };
        $rootScope.confirmWindow(confirmParams, function (data) {
            if (data) {
                // isDel 0：保存（默认） 1：删除
                var postParams = {
                    "id": row.id,
                    "isDel": 1
                };
                var url = matrix_product_url + "/need/saveNeed";
                $http({
                    method: "post",
                    url: url,
                    data: JSON.stringify(postParams),
                    headers: {"Content-Type": "application/json"}
                }).success(function (result) {
                    if (result.code == "0") {
                        setPie();
                        setSpline('ACCEPT');
                        lodash.remove($scope.tableData, {"id": row.id});
                        lodash.remove($scope.info.allData, {"id": row.id});
                        getUserAcceptCount();
                        $rootScope.toasterSuccessInfo("删除成功！");
                    } else {
                        $rootScope.toasterErrorInfo(result.desc);
                    }
                });
            }
        });
    };

    // 回退
    $scope.clickFALLBACK = function (row) {
        var confirmParams = {
            "titleData": "提示",
            "bodyData": "确定回退需求【" + row.title + "】吗？"
        };
        $rootScope.confirmWindow(confirmParams, function (data) {
            if (data) {
                var postParams = {
                    "id": row.id,
                    "status": "FALLBACK"
                };
                var url = matrix_product_url + "/need/saveNeed";
                $http({
                    method: "post",
                    url: url,
                    data: JSON.stringify(postParams),
                    headers: {"Content-Type": "application/json"}
                }).success(function (result) {
                    if (result.code == "0") {
                        setPie();
                        setSpline('ACCEPT');
                        var crtRow = lodash.findWhere($scope.tableData, {"id": row.id});
                        var crtRowTab = lodash.findWhere($scope.info.allData, {"id": row.id});
                        crtRow.status = "FALLBACK";
                        crtRow.statusName = "已回退";
                        crtRowTab.status = "FALLBACK";
                        crtRowTab.statusName = "已回退";
                        $rootScope.toasterSuccessInfo("回退成功！");
                    } else {
                        $rootScope.toasterErrorInfo(result.desc);
                    }
                });
            }
        });
    };

    // 添加受理
    $scope.acceptDemand = function (row) {
        var confirmParams = {
            "titleData": "提示",
            "bodyData": "确定受理需求【" + row.title + "】吗？"
        };
        $rootScope.confirmWindow(confirmParams, function (data) {
            if (data) {
                var postParams = {
                    "id": row.id,
                    "status": "ACCEPT",
                    "acceptAccount": getUserAccount(),
                    "acceptName": getUserName()
                };
                var url = matrix_product_url + "/need/saveNeed";
                $http({
                    method: "post",
                    url: url,
                    data: JSON.stringify(postParams),
                    headers: {"Content-Type": "application/json"}
                }).success(function (result) {
                    if (result.code == "0") {
                        setPie();
                        setSpline('ACCEPT');
                        var crtRow = lodash.findWhere($scope.tableData, {"id": row.id});
                        var crtRowTab = lodash.findWhere($scope.info.allData, {"id": row.id});
                        crtRow.status = "ACCEPT";
                        crtRow.statusName = "待确认";
                        crtRowTab.status = "ACCEPT";
                        crtRowTab.statusName = "待确认";
                        crtRow.acceptAccount = getUserAccount();
                        crtRow.acceptName = getUserName();
                        crtRowTab.acceptAccount = getUserAccount();
                        crtRowTab.acceptName = getUserName();
                        getUserAcceptCount();
                        $rootScope.toasterSuccessInfo("需求受理成功！");
                    } else {
                        $rootScope.toasterErrorInfo(result.desc);
                    }
                });
            }
        });
    };

    // 部门评审
    $scope.reviewNeed = function (row) {
        window.location.href = "#/app/need/addNeed/edit/"+ row.id +"/"+ ($stateParams.accept || "") +"/"+ ($stateParams.appointAccept || "");
    };
    // 取消受理
    $scope.cancelDemand = function (row) {
        var confirmParams = {
            "titleData": "提示",
            "bodyData": "确定取消受理需求【" + row.title + "】吗？"
        };
        $rootScope.confirmWindow(confirmParams, function (data) {
            if (data) {
                var postParams = {
                    "id": row.id,
                    "status": "NO_ACCEPT"
                };
                var url = matrix_product_url + "/need/saveNeed";
                $http({
                    method: "post",
                    url: url,
                    data: JSON.stringify(postParams),
                    headers: {"Content-Type": "application/json"}
                }).success(function (result) {
                    if (result.code == "0") {
                        setPie();
                        setSpline('ACCEPT');
                        var crtRow = lodash.findWhere($scope.tableData, {"id": row.id});
                        var crtRowTab = lodash.findWhere($scope.info.allData, {"id": row.id});
                        crtRow.status = "NO_ACCEPT";
                        crtRow.statusName = "待评审";
                        crtRowTab.status = "NO_ACCEPT";
                        crtRowTab.statusName = "待评审";
                        crtRow.acceptAccount = "";
                        crtRow.acceptName = "";
                        crtRowTab.acceptAccount = "";
                        crtRowTab.acceptName = "";
                        getUserAcceptCount();
                        $rootScope.toasterSuccessInfo("取消成功！");
                    } else {
                        $rootScope.toasterErrorInfo(result.desc);
                    }
                });
            }
        });
    }

    // 评价
    $scope.clickStar = function (row) {
        var confirmParams = {
            "titleData": "提示",
            "bodyData": "确定要添加评价吗？"
        };
        $rootScope.confirmWindow(confirmParams, function (data) {
            if (data) {
                $("i[data-id=" + row.id + "]").css("display", "block");
                $(".rating[data-id=" + row.id + "]").css("display", "none");
                var url = matrix_product_url + "/need/updateNeedStar?id=" + row.id + "&star=" + row.star;
                $http.get(url).success(function (result) {
                    if (result.code == "0") {
                        $("i[data-id=" + row.id + "]").css("display", "none");
                        $(".rating[data-id=" + row.id + "]").css("display", "block");
                        row.starType = result.data.starType;
                        row.status = result.data.status;
                        row.statusName = "已结束";
                        $rootScope.toasterSuccessInfo("评价成功！");
                    } else {
                        $rootScope.toasterErrorInfo("评价失败，请联系管理员！");
                    }
                });
            }else {

            }
        }, function () {
            var url = matrix_product_url + "/need/getNeeds?id=" + row.id+"&isOnline=true";
            $http.get(url).success(function (result) {
                if (result.code == "0") {
                    row.star = result.data[0].star;
                }
            });
        });
    }

    //获取全部用户
    function getAllUser(type) {
        var url = beetle_auth_url + "/user/?token_id=" + getTokenId();
        // if(type) {
        //     url = url + "&role_name="+ type;
        // }
        $http.get(url).success(function (result) {
            if (result.success) {
                if (result.data) {
                    if(type) {
                        var array = [];
                        var masterArray = [];
                        angular.forEach(result.data, function (data) {
                            data.crtname = data.realname;
                            array.push(data);
                            masterArray.push(data);
                        });
                        setHeaderToNeedMaster(masterArray);
                        setHeaderToAccount(array);
                    } else {
                        var array = [];
                        var appointArray = [];
                        angular.forEach(result.data, function (data) {
                            data.crtname = data.realname;
                            array.push(data);
                            appointArray.push(data);
                        });
                        setHeaderCreator(array);
                        setAppointAccept(appointArray);
                    }
                } else {
                    $rootScope.toasterErrorInfo("获取用户数据错误！");
                }
            } else {
                $rootScope.toasterErrorInfo(result.msg);
            }
        });
    };

    setHeaderOrigin();

    // 设置需求来源---假数据
    function setHeaderOrigin() {
        var sourceList = [{"crtname": "全部来源", "index": 0}];
        angular.forEach($scope.info.sourceList, function(source) {
            source.crtname = source.value;
            sourceList.push(source);
        });
        var originSelectEle = {
            status: true,
            items: sourceList,
            // items: [{"crtname": "客户", "id": 1}, {"crtname": "商务中心部", "id": 2}, {"crtname": "系统工程", "id": 3}],
            prompt: "请选择需求来源",
            selectedItem: {"crtname": "全部来源", "key": 0},
            func: function (item) {
                $scope.info.searchC.source = item.key;
                searchByKeyword();
            }
        };

        $scope.settings.uiSltEle.push(originSelectEle);
    }

    // 设置提出人
    function setHeaderCreator(userArray) {
        userArray.unshift({"crtname": "所有提出人", "id": 0});
        var proposerAccount = "";
        if ($scope.urlProposer) {
            var crtAccount = lodash.findWhere(userArray, {"account": $scope.urlProposer});
            crtAccount.crtname = crtAccount.realname;
            proposerAccount = crtAccount;
        } else {
            proposerAccount = {"crtname": "所有提出人", "id": 0};
        }
        var userSelectEle = {
            status: true,
            items: userArray,
            prompt: "请选择需求提出人",
            selectedItem: proposerAccount,
            func: function (item) {
                $scope.info.searchC.proposerAccount = item.account;
                searchByKeyword();
            }
        };
        if(!$scope.urlMyAccount){
            $scope.settings.uiSltEle.push(userSelectEle);
        }
    }

    // setHeaderClass();

    // 设置PDM分组---假数据
    // function setHeaderClass(pdmGroups) {
    //     var groupSelectEle = {
    //         status: true,
    //         items: [{"crtname": "分组01", "id": 1}],
    //         prompt: "请选择PDM工作组",
    //         selectedItem: {"crtname": "全部分组", "id": 0},
    //         func: function (item) {
    //             searchByKeyword();
    //         }
    //     };
    //
    //     if ($rootScope.isMatrixCusRole("pdm")) {
    //         $scope.settings.uiSltEle.push(groupSelectEle);
    //     }
    // }

    // 设置pdm负责人
    function setHeaderToAccount(toAccountAry) {
        toAccountAry.unshift({"crtname": "所有PDM负责人", "id": 0});
        var fondnessPdmAccount = "";
        if ($scope.urlPdmAcount) {
            var crtAccount = lodash.findWhere(toAccountAry, {"account": $scope.urlPdmAcount});
            crtAccount.crtname = crtAccount.realname;
            fondnessPdmAccount = crtAccount;
        } else {
            fondnessPdmAccount = {"crtname": "所有PDM负责人", "id": 0};
        }
        var userSelectEle = {
            status: true,
            items: toAccountAry,
            prompt: "请选择PDM负责人",
            selectedItem: fondnessPdmAccount,
            func: function (item) {
                $scope.info.searchC.pdmAccount = item.account;
                searchByKeyword();
            }
        };

        if ($rootScope.isMatrixCusRole("pdm") && !$scope.urlMyAccount) {
            $scope.settings.uiSltEle.push(userSelectEle);
        }
    };

    // 设置指定受理人
    function setAppointAccept(array) {
        array.unshift({"crtname": "所有指定受理人", "id": 0});
        var fondnessAppointAcceptAccount = "";
        if ($scope.urlAppointAcceptAccount) {
            var crtAccount = lodash.findWhere(array, {"account": $scope.urlAppointAcceptAccount});
            crtAccount.crtname = crtAccount.realname;
            fondnessAppointAcceptAccount = crtAccount;
        } else {
            fondnessAppointAcceptAccount = {"crtname": "所有指定受理人", "id": 0};
        }
        var appointAcceptSelectEle = {
            status: true,
            items: array,
            prompt: "请选择指定受理人",
            selectedItem: fondnessAppointAcceptAccount,
            func: function (item) {
                $scope.info.searchC.appointAcceptAccount = item.account;
                searchByKeyword();
            }
        };

        if ($rootScope.isMatrixCusRole("pdm") && !$scope.urlMyAccount) {
            $scope.settings.uiSltEle.push(appointAcceptSelectEle);
        }
    };

    // 设置全部受理人
    function setHeaderToNeedMaster(needMasterArray) {
        needMasterArray.unshift({"crtname": "所有受理人", "id": 0})
        var fondnessNeedMasterAccount = "";
        if ($scope.urlAcceptAccount) {
            var crtAccount = lodash.findWhere(needMasterArray, {"account": $scope.urlAcceptAccount});
            crtAccount.crtname = crtAccount.realname;
            fondnessNeedMasterAccount = crtAccount;
        } else {
            fondnessNeedMasterAccount = {"crtname": "所有受理人", "id": 0};
        }
        var needMasterSelectEle = {
            status: true,
            items: needMasterArray,
            prompt: "请选择受理人",
            selectedItem: fondnessNeedMasterAccount,
            func: function (item) {
                $scope.info.searchC.needMasterAccount = item.account;
                searchByKeyword();
            }
        };

        if ($rootScope.isMatrixCusRole("pdm") && !$scope.urlMyAccount) {
            $scope.settings.uiSltEle.push(needMasterSelectEle);
        }
    }

    // 查询关键字
    function searchByKeyword() {
        var url = matrix_product_url + "/need/getNeeds";
        var urlArray = [];
        $scope.info.searchC.showOnline =true
        if($scope.urlMyAccount){
            urlArray.push({"type": "myAccount", "param": $scope.urlMyAccount})
        }
        if($scope.info.searchC.showOnline){
            urlArray.push({"type": "isOnline", "param": $scope.info.searchC.showOnline})
        }
        if ($scope.info.searchC.source) {
            urlArray.push({"type": "source", "param": $scope.info.searchC.source})
        }
        if ($scope.info.searchC.showOnline) {
            urlArray.push({"type": "isOnline", "param": $scope.info.searchC.showOnline})
        }
        if ($scope.info.searchC.startDate) {
            urlArray.push({"type": "startDate", "param": $scope.info.searchC.startDate})
        }
        if ($scope.info.searchC.proposerAccount) {
            urlArray.push({"type": "proposerAccount", "param": $scope.info.searchC.proposerAccount})
        }
        if ($scope.info.searchC.pdmAccount) {
            urlArray.push({"type": "pdmAccount", "param": $scope.info.searchC.pdmAccount})
        }
        if ($scope.info.searchC.needMasterAccount) {
            urlArray.push({"type": "acceptAccount", "param": $scope.info.searchC.needMasterAccount})
        }
        if ($scope.info.searchC.appointAcceptAccount) {
            urlArray.push({"type": "appointAcceptAccount", "param": $scope.info.searchC.appointAcceptAccount})
        }
        if ($scope.info.searchC.keyword) {
            urlArray.push({"type": "keyword", "param": $scope.info.searchC.keyword})
        }
        url = $rootScope.setUrlParams(url, urlArray);
        $http.get(url).success(function (result) {
            if (result.code == "0") {
                angular.forEach(result.data, function (res) {
                    // 转换时间、状态、优先级
                    res.createTime = timestampToTime(res.createTime, true);
                    var statusItem = lodash.findWhere(config_need_status, {"key": res.status});
                    if (statusItem) {
                      res.statusName = statusItem.tabDesc;
                    }
                    var fallbackReasonItem = res.fallbackReason == null ? "" : lodash.findWhere(config_need_return, {"key": res.fallbackReason});
                    res.fallbackReasonName = fallbackReasonItem == undefined ? "" : fallbackReasonItem.value;
                    var levelItem = lodash.findWhere(config_need_level, {"key": res.deptPriority});
                    res.levelName = levelItem ? levelItem.value : "";
                    var sourceItem = lodash.findWhere($scope.info.sourceList, {"key": res.source});
                    res.sourceName = sourceItem ? sourceItem.value : res.source;
                    res.pdms = "";
                    if (res.needPdm.length > 0) {
                        angular.forEach(res.needPdm, function (pdm, index) {
                            res.pdms += pdm.realname + (res.needPdm.length == index + 1 ? "" : " / ");
                        });
                    }
                });

                $scope.info.allData = $filter('orderBy')(result.data, "createTime", true);
                $scope.clickTab($scope.info.selectTab || "ALL");
            } else {
                $rootScope.toasterErrorInfo(result.desc);
            }
        });
    };


    // 新建需求
    function createNewDemand() {
        window.location.href = "#/app/need/addNeed/add//"+ ($stateParams.accept || "") +"/"+ ($stateParams.appointAccept || "");
    };

    // 编辑受理需求
    function editAcceptDemand() {
        if ($scope.info.acceptCount > 0) {
            window.location.href = "#/app/need/acceptList/"+ ($stateParams.accept || "") +"/"+ ($stateParams.appointAccept || "");
        } else {
            $rootScope.toasterWarningInfo("请先受理需求，然后查看！");
        }
    };

    // 点击标题展开详情--unused
    $scope.clickTitle = function (row) {
        var tabIndex = row.$$index;
        var devLength = $(".dt-body-scroller").children("div.dt-row").length;
        $timeout(function () {
            for (var i = 0; i < devLength; i++) {
                if (i > tabIndex) {
                    var padding = 100 + 40 * i;
                    $(".dt-row[tabindex=" + i + "]").css("transform", "translate3d(0px, " + padding + "px, 0px)");
                } else {
                    var padding = 40 * i;
                    $(".dt-row[tabindex=" + i + "]").css("transform", "translate3d(0px, " + padding + "px, 0px)");
                }
            }
        });
    };

    // 触发关闭popover方法--unused
    $rootScope.$on('ngDropover.closing', function (event, dropObj) {
        var devLength = $(".dt-body-scroller").children("div.dt-row").length;
        for (var i = 0; i < devLength; i++) {
            var padding = 40 * i;
            $(".dt-row[tabindex=" + i + "]").css("transform", "translate3d(0px, " + padding + "px, 0px)");
        }
    });
}]);